/**
 * Created by linyi on 2019/3/4
 */
import request from '@/utils/api'

// action
export const CALL_API = 'CALL-API'

function callApi(config) {
  return request(config)
}

// 调用 api 的 action 为：{ 'CALL-API': { types: [], payload: {} } }
export default () => next => action => {
  const callAPI = action[CALL_API]
  if (typeof callAPI === 'undefined') {
    return next(action)
  }

  const { types, payload } = callAPI
  const [requestType, successType, failureType] = types

  const actionWith = data => {
    const finalAction = { ...action, ...data }
    delete finalAction[CALL_API]
    return finalAction
  }

  // dispatch 请求 action，如 设置 loading 为 true
  next(actionWith({ type: requestType }))

  return callApi(payload).then(
    json => next(actionWith({ type: successType, payload: json })),
    err => next(actionWith({ type: failureType, payload: err || '未知的错误' }))
  )
}
